package com.kindnesslibrary.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.widget.EditText;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.security.MessageDigest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by lenovo on 2017/5/30.
 * 我的工具类
 */
public class MyUtil {

    public static MyUtil utils;

    private MyUtil() {

    }

    public synchronized static MyUtil getInstance() {
        if (utils == null)
            utils = new MyUtil();
        return utils;
    }

    /**
     * 判断网络是否连接，返回false为没有任何连接
     *
     * @param context 上下文
     * @return boolean
     */
    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 是否WI-FI连接状态
     *
     * @param mContext
     * @return 0:无网络;1:Wi-Fi连接;2:移动网络连接
     */
    public int isWifiNetwork(Context mContext) {
        if (!isNetworkConnected(mContext)) {
            return 0;
        }
        ConnectivityManager connectivityManager = (ConnectivityManager) mContext
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null
                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            return 1;
        }
        return 2;
    }

    /**
     * 获取内部版本号
     *
     * @param context 上下文
     * @return String
     */
    public int getVersionCode(Context context) {
        int versionCode = 1;
        try {
            PackageInfo pi = context.getPackageManager()
                    .getPackageInfo(context.getPackageName(),
                            PackageManager.GET_CONFIGURATIONS);
            versionCode = pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取设备号（IMEI）
     *
     * @param context 上下文
     * @return String 设备号
     */
    public String getDeviceId(Context context) {
        TelephonyManager tm = (TelephonyManager) context
                .getSystemService(Context.TELEPHONY_SERVICE);
        StringBuffer dwc = new StringBuffer();
        try {
            dwc.append(tm.getDeviceId());
        } catch (Exception e) {
        }
        dwc.append(Build.BOARD)
                .append(Build.BRAND)
                .append(Build.DEVICE)
                .append(Build.DISPLAY)
                .append(Build.HOST)
                .append(Build.ID)
                .append(Build.MANUFACTURER)
                .append(Build.MODEL)
                .append(Build.PRODUCT)
                .append(Build.TAGS)
                .append(Build.TYPE)
                .append(Build.USER)
                .append(Settings.Secure
                        .getString(context.getContentResolver(), Settings.Secure.ANDROID_ID));
        String d = MD5(dwc.toString());
        return d;
    }

    /**
     * MD5加密，32位
     *
     * @param url 需加密的字符串
     * @return 加密后的字符串
     */
    public String MD5(String url) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
                'E', 'F'};
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            // e.printStackTrace();
            return getFile(url);
        }
        md5.update(url.getBytes());
        byte[] md5Bytes = md5.digest();
        // 把密文转换成十六进制的字符串形式
        int j = md5Bytes.length;
        char str[] = new char[j * 2];
        int k = 0;
        for (int i = 0; i < j; i++) {
            byte byte0 = md5Bytes[i];
            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
            str[k++] = hexDigits[byte0 & 0xf];
        }
        return new String(str);
    }

    /**
     * 将URL转成能够识别的目录
     */
    public String getFile(String url) {
        String path = url;
        if (path.contains("?")) {
            path = path.replace("?", "_");
        }
        if (path.contains("/")) {
            path = path.replace("/", "_");
        }
        if (path.contains(".")) {
            path = path.replace(".", "_");
        }
        return path;
    }

    /**
     * 压缩图片
     *
     * @param newW 新图片宽度
     * @param newH 新图片高度
     * @param path 本地图片地址
     * @return
     */
    public BitmapFactory.Options reduceBitmap(int newW, int newH, String path) {
        if (path == null || path.length() == 0) {
            return null;
        }
        BitmapFactory.Options op = new BitmapFactory.Options();
        op.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, op);
        int oldW = op.outWidth;
        int oldH = op.outHeight;
        int size = 1;// 默认不缩放
        if (oldW > oldH) {// 宽大于高的情况(横版相机)
            if (newW > newH) {
                if (oldW > newW) {
                    size = oldW / newW;
                }
            } else {
                if (oldW > newH) {
                    size = oldW / newH;
                }
            }
        } else {// 高大于宽的情况(竖版相机)
            if (newH > newW) {
                if (oldH > newH) {
                    size = oldH / newH;
                }
            } else {
                if (oldH > newW) {
                    size = oldH / newW;
                }
            }
        }
        BitmapFactory.Options op1 = new BitmapFactory.Options();
        op1.inJustDecodeBounds = false;
        op1.inSampleSize = size;
        return op1;
    }

    /**
     * 压缩图片并返回压缩后的图片地址
     *
     * @param context 上下文
     * @param newW    新图片宽度
     * @param newH    新图片高度
     * @param path    本地图片地址
     * @return 保存成功后的地址，保存失败返回null
     */
    public String reduceBitmap(Context context, int newW, int newH, String path) {
        BitmapFactory.Options op = reduceBitmap(newW, newH, path);
        if (op == null) {
            return null;
        }

        Bitmap bm = BitmapFactory.decodeFile(path,
                op);
        int degree = getExifOrientation(path);
        if (degree == 90 || degree == 180 || degree == 270) {
            Matrix matrix = new Matrix();
            matrix.postRotate(degree);
            if (bm == null) {
                return null;
            }
            bm = Bitmap.createBitmap(bm, 0, 0, op.outWidth, op.outHeight, matrix, true);
        }
        return saveBitmap(context, bm);
    }

    public Bitmap compressBitmap(Context context, int newW, int newH, String path) {
        BitmapFactory.Options op = reduceBitmap(newW, newH, path);
        if (op == null) {
            return null;
        }

        Bitmap bm = BitmapFactory.decodeFile(path,
                op);
        int degree = getExifOrientation(path);
        if (degree == 90 || degree == 180 || degree == 270) {
            Matrix matrix = new Matrix();
            matrix.postRotate(degree);
            if (bm == null) {
                return null;
            }
            bm = Bitmap.createBitmap(bm, 0, 0, op.outWidth, op.outHeight, matrix, true);
        }
        return bm;
    }

    /**
     * 保存图片到本地缓存“images_data”目录中
     *
     * @param context 上下文
     * @param bm      需要保存的Bitmap对象
     * @return 保存成功后的地址，保存失败返回null
     */
    public String saveBitmap(Context context, Bitmap bm) {
        if (bm == null) {
            return null;
        }
        File file = getCache(context, Contants.CACHE_PATH + "/images_data");
        if (file == null)
            return null;
        if (!file.exists()) {
            file.mkdirs();
        }
        file = new File(file.getPath() + "/"
                + String.valueOf(System.currentTimeMillis()) + ".jpeg");
        if (file == null)
            return null;
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            fos.flush();
            fos.close();
            if (bm != null) {
                bm.recycle();
                bm = null;
            }
            BitmapFactory.Options op = new BitmapFactory.Options();
            op.inSampleSize = 16;
            bm = BitmapFactory.decodeFile(file.getPath());
            if (bm == null) {
                return null;
            }
            bm.recycle();
            bm = null;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return file.getPath();
    }

    /**
     * 查看密码
     *
     * @param mEditText
     * @param isView    是否查看,true查看,false隐藏
     */
    public void viewPassword(EditText mEditText, boolean isView) {
        if (mEditText == null) {
            throw new NullPointerException();
        } else {
            int cursorPosition = mEditText.getSelectionStart();
            if (isView) {
                mEditText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                mEditText.setSelection(cursorPosition);
            } else {
                mEditText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                mEditText.setSelection(cursorPosition);
            }
        }
    }

    /**
     * 是否正确手机号
     *
     * @param mobiles
     * @return
     */
    public boolean isMobileNO(String mobiles) {
        Pattern p = Pattern
                .compile("^((13[0-9])|(14[0-9])|(15[^4,\\D])|(17[0-9])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 获取外部缓存目录中的自定义目录
     *
     * @param context 上下文
     * @param path    自定义目录
     * @return File
     */
    public File getCache(Context context, String path) {
        File file = null;
        try {
            if (Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED)) {
                file = new File(context.getExternalCacheDir().getPath() + "/"
                        + path);
            } else {
                file = new File(context.getCacheDir() + "/" + path);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (file == null)
            return null;
        if (!file.exists()) {
            if (!file.mkdirs()) {
                return null;
            }
        }
        return file;
    }

    /**
     * 获取图片方向
     *
     * @param filePath 图片地址
     * @return
     */
    public int getExifOrientation(String filePath) {
        int degree = 0;
        if (filePath == null)
            return degree;
        ExifInterface exif = null;
        try {
            exif = new ExifInterface(filePath);
        } catch (IOException ex) {
            // MmsLog.e(ISMS_TAG, "getExifOrientation():", ex);
        }

        if (exif != null) {
            int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, -1);
            if (orientation != -1) {
                // We only recognize a subset of orientation tag values.
                switch (orientation) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        degree = 90;
                        break;

                    case ExifInterface.ORIENTATION_ROTATE_180:
                        degree = 180;
                        break;

                    case ExifInterface.ORIENTATION_ROTATE_270:
                        degree = 270;
                        break;

                    default:
                        break;
                }
            }
        }

        return degree;
    }

    /**
     * 获取虚拟按键高度
     *
     * @param context
     * @return
     */
    public int getNavigationBarHeight(Context context) {
        int navigationBarHeight = 0;
        Resources rs = context.getResources();
        int id = rs.getIdentifier("navigation_bar_height", "dimen", "android");
        if (id > 0 && isDeviceHasNavigationBar(context)) {
            navigationBarHeight = rs.getDimensionPixelSize(id);
        }
        return navigationBarHeight;
    }

    /**
     * 获取状态栏高度
     *
     * @param mContext
     * @return
     */
    public int getStatusBarHeight(Context mContext) {
        int statusBarHeight = 0;
        Class<?> c = null;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            Object obj = c.newInstance();
            Field field = c.getField("status_bar_height");
            int x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = mContext.getResources().getDimensionPixelSize(x);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        return statusBarHeight;
    }

    /**
     * 判断是否存在虚拟按键
     *
     * @param context
     * @return
     */
    public boolean isDeviceHasNavigationBar(Context context) {
        boolean hasNavigationBar = false;
        Resources rs = context.getResources();
        int id = rs
                .getIdentifier("config_showNavigationBar", "bool", "android");
        if (id > 0) {
            hasNavigationBar = rs.getBoolean(id);
        }
        try {
            Class systemPropertiesClass = Class
                    .forName("android.os.SystemProperties");
            Method m = systemPropertiesClass.getMethod("get", String.class);
            String navBarOverride = (String) m.invoke(systemPropertiesClass,
                    "qemu.hw.mainkeys");
            if ("1".equals(navBarOverride)) {
                hasNavigationBar = false;
            } else if ("0".equals(navBarOverride)) {
                hasNavigationBar = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            hasNavigationBar = false;
        }

        return hasNavigationBar;
    }

}
